// (c) Copyright Damian Mehers http://damianblog.com/
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using MceFM.Last;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;

namespace MceFM.Code {
  public class MceFMAddIn : IAddInModule, IAddInEntryPoint {
    private static HistoryOrientedPageSession s_session;

    private readonly Settings settings = new Settings();

    public void Initialize(Dictionary<string, object> appInfo, Dictionary<string, object> entryPointInfo) {}

    public void Uninitialize() {}

    private void InitializeTrace(AddInHost host, string category) {
      try {
        category = category.Replace('\\', '_');
        TraceListener traceListener = new TextWriterTraceListener(Util.GetTraceFileName());
        Trace.AutoFlush = true;
        Trace.Listeners.Add(traceListener);
        Trace.TraceInformation("MceFM AddIn starting ... category is '{0}'", category);
        Trace.Flush();
      } catch(Exception ex) {
        host.MediaCenterEnvironment.Dialog(ex.Message, settings.DialogTitleForErrors, DialogButtons.Ok, 0, true);
      }
    }

    public void Launch(AddInHost host) {
      try {
        string category = ((string)host.ApplicationContext.EntryPointInfo[settings.CategoryEntryPoint]).ToLower();

        InitializeTrace(host, category);


        if(category == settings.BackgroundCategory) {
          RunBackground(host);
          return;
        }


        if(category == settings.MoreWithThisArtistCategory || 
          category == settings.MoreWithThisGenreCategory ||
          category == settings.MoreWithThisAlbumCategory ||
          category == settings.MoreWithThisSongCategory) {


          HandleMore(host, category);
          return;
        }

        ShowPage(settings.MainPage);
      } catch(Exception ex) {
        Trace.TraceError("Unexpected error in MceFMAddIn.Launch: {0}", ex);
      } finally {
        Trace.Flush();
      }
    }

    private void HandleMore(AddInHost host, string category) {
      Options options = new Options();
      if(string.IsNullOrEmpty(options.SavedLastFmUsername) || string.IsNullOrEmpty(options.SavedLastFmPasswordHash)) {
        host.MediaCenterEnvironment.Dialog(settings.EnterUsernamePassword,
                                           settings.DialogTitle,
                                           DialogButtons.Ok,
                                           0,
                                           true);
        ShowPage(settings.OptionsPage);
        return;
      }

      bool loginFailed = HandleMorePlay(host, category);
      Trace.TraceError("Login failed:{0}", loginFailed);
      if(loginFailed) {
        ShowPage(settings.OptionsPage);
      }
    }


    private static void ShowPage(string page) {
      s_session = new HistoryOrientedPageSession();
      s_session.GoToPage(page);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="host"></param>
    /// <param name="category"></param>
    /// <returns>true if login failed</returns>
    private bool HandleMorePlay(AddInHost host, string category) {
      string what;
      string mediaContextKey;
      if(category == settings.MoreWithThisGenreCategory) {
        what = settings.PlayGenreMcmlString;
        mediaContextKey = settings.GenreMediaContextString;
      } else {
        what = settings.PlayArtistMcmlString;
        mediaContextKey = settings.AlbumArtistMediaContextString;
      }
      foreach(KeyValuePair<string, object> keyValuePair in host.MediaContext) {
        Trace.TraceInformation("KP {0}={1}", keyValuePair.Key, keyValuePair.Value);
      }
      string name = (string)host.MediaContext[mediaContextKey];
      if(string.IsNullOrEmpty(name)) {
        host.MediaCenterEnvironment.Dialog("Media Center has passed an empty name to MceFM.  Please try something else",
                                   settings.DialogTitle,
                                   DialogButtons.Ok,
                                   0,
                                   true);
        return false;
      }

      Player player = new Player();
      return player.Play(host, what, name);
    }


    private void RunBackground(AddInHost host) {

      try {
        Options options = new Options();

        Server server = new Server(Util.ServerStartUrl, options.SavedLastFmUsername, options.SavedLastFmPasswordHash );

        server.Start();
        while(true) {
          Thread.Sleep(300000);
        }
      } catch(Exception ex) {
        host.MediaCenterEnvironment.Dialog(ex.Message, "Unexpected MceFM Background Application Error", DialogButtons.Ok, 500, false);
        Trace.TraceError("Unexpected error in RunBackground: {0}", ex.Message);
        Trace.TraceError("Unexpected error in RunBackground:  Stack is {0}", ex.StackTrace);
        Trace.Flush();
      }
    }
  }
}